<template>
  <div class="related-info">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">相关信息管理</h2>
      <p class="page-description">管理水库运营相关的各类信息资料</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statsData.totalContacts }}</div>
              <div class="stat-label">联系人数量</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statsData.totalDocuments }}</div>
              <div class="stat-label">文档资料</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Reading /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statsData.totalKnowledge }}</div>
              <div class="stat-label">知识条目</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Link /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statsData.totalLinks }}</div>
              <div class="stat-label">外部链接</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <el-tabs v-model="activeTab" type="card" @tab-change="handleTabChange">
        <!-- 联系人管理 -->
        <el-tab-pane label="联系人管理" name="contacts">
          <div class="tab-content">
            <!-- 查询条件 -->
            <el-card shadow="hover" style="margin-bottom: 8px">
              <el-form :model="contactQuery" inline>
                <el-form-item label="姓名">
                  <el-input
                    v-model="contactQuery.name"
                    placeholder="请输入姓名"
                    clearable
                    style="width: 200px"
                  />
                </el-form-item>
                <el-form-item label="部门">
                  <el-select v-model="contactQuery.department" placeholder="请选择部门" clearable style="width: 150px">
                    <el-option label="管理部" value="management" />
                    <el-option label="技术部" value="technical" />
                    <el-option label="安全部" value="safety" />
                    <el-option label="维护部" value="maintenance" />
                    <el-option label="外部单位" value="external" />
                  </el-select>
                </el-form-item>
                <el-form-item label="职位">
                  <el-select v-model="contactQuery.position" placeholder="请选择职位" clearable style="width: 120px">
                    <el-option label="主管" value="supervisor" />
                    <el-option label="工程师" value="engineer" />
                    <el-option label="技术员" value="technician" />
                    <el-option label="操作员" value="operator" />
                    <el-option label="其他" value="other" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" :icon="Search" @click="searchContacts">查询</el-button>
                  <el-button :icon="Refresh" @click="resetContactQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 操作按钮 -->
            <el-card shadow="never" class="action-card">
              <el-row :gutter="16">
                <el-col :span="24">
                  <el-button type="primary" plain :icon="Plus" @click="handleAddContact">新增联系人</el-button>
                  <el-button plain :icon="Download" @click="exportContacts">导出通讯录</el-button>
                </el-col>
              </el-row>
            </el-card>

            <!-- 数据表格 -->
            <el-card shadow="hover" class="table-card">
              <el-table :data="contactList" border style="width: 100%">
                <el-table-column prop="name" label="姓名" width="120" />
                <el-table-column prop="department" label="部门" width="120">
                  <template #default="{ row }">
                    <el-tag :type="getDepartmentTag(row.department)" size="small">
                      {{ getDepartmentText(row.department) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="position" label="职位" width="120" />
                <el-table-column prop="phone" label="联系电话" width="150" />
                <el-table-column prop="email" label="邮箱" width="200" />
                <el-table-column prop="office" label="办公地点" width="150" />
                <el-table-column prop="specialties" label="专业领域"/>
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getContactStatusTag(row.status)" size="small">
                      {{ getContactStatusText(row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="270" fixed="right">
                  <template #default="{ row }">
                    <el-button type="primary" link :icon="View" @click="viewContactDetail(row)">查看</el-button>
                    <el-button type="primary" link :icon="Edit" @click="editContact(row)">编辑</el-button>
                    <el-button type="success" link @click="callContact(row)">拨打</el-button>
                    <el-button type="danger" link :icon="Delete" @click="deleteContact(row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>

            <!-- 分页 -->
            <div class="pagination-section">
              <el-pagination
                v-model:current-page="contactPagination.currentPage"
                v-model:page-size="contactPagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="contactPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleContactSizeChange"
                @current-change="handleContactCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- 文档资料 -->
        <el-tab-pane label="文档资料" name="documents">
          <div class="tab-content">
            <!-- 查询条件 -->
            <div class="query-section">
              <el-form :model="documentQuery" inline>
                <el-form-item label="文档名称">
                  <el-input
                    v-model="documentQuery.name"
                    placeholder="请输入文档名称"
                    clearable
                    style="width: 200px"
                  />
                </el-form-item>
                <el-form-item label="文档类型">
                  <el-select v-model="documentQuery.type" placeholder="请选择类型" clearable style="width: 150px">
                    <el-option label="技术文档" value="technical" />
                    <el-option label="管理文档" value="management" />
                    <el-option label="操作手册" value="manual" />
                    <el-option label="培训资料" value="training" />
                    <el-option label="其他" value="other" />
                  </el-select>
                </el-form-item>
                <el-form-item label="上传时间">
                  <el-date-picker
                    v-model="documentQuery.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    style="width: 240px"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" :icon="Search" @click="searchDocuments">查询</el-button>
                  <el-button :icon="Refresh" @click="resetDocumentQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 操作按钮 -->
            <el-card shadow="never" class="action-card">
              <el-row :gutter="16">
                <el-col :span="24">
                  <el-button type="primary" plain :icon="Plus" @click="handleAddDocument">上传文档</el-button>
                  <el-button plain :icon="FolderOpened" @click="createFolder">新建文件夹</el-button>
                </el-col>
              </el-row>
            </el-card>

            <!-- 文档列表 -->
            <div class="document-grid">
              <div
                v-for="doc in documentList"
                :key="doc.id"
                class="document-item"
                @click="viewDocument(doc)"
              >
                <div class="document-icon">
                  <el-icon><Document /></el-icon>
                </div>
                <div class="document-info">
                  <div class="document-name">{{ doc.name }}</div>
                  <div class="document-meta">
                    <span class="document-type">{{ getDocumentTypeText(doc.type) }}</span>
                    <span class="document-size">{{ formatFileSize(doc.size) }}</span>
                  </div>
                  <div class="document-date">{{ doc.uploadDate }}</div>
                </div>
                <div class="document-actions">
                  <el-button type="primary" link @click.stop="downloadDocument(doc)">
                    <el-icon><Download /></el-icon>
                  </el-button>
                  <el-button type="primary" link @click.stop="editDocument(doc)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button type="danger" link @click.stop="deleteDocument(doc)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 分页 -->
            <div class="pagination-section">
              <Pagination
                :current-page="documentPagination.currentPage"
                :page-size="documentPagination.pageSize"
                :total="documentPagination.total"
                @pagination="handleDocumentPagination"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- 知识库 -->
        <el-tab-pane label="知识库" name="knowledge">
          <div class="tab-content">
            <!-- 查询条件 -->
            <div class="query-section">
              <el-form :model="knowledgeQuery" inline>
                <el-form-item label="标题">
                  <el-input
                    v-model="knowledgeQuery.title"
                    placeholder="请输入标题"
                    clearable
                    style="width: 200px"
                  />
                </el-form-item>
                <el-form-item label="分类">
                  <el-select v-model="knowledgeQuery.category" placeholder="请选择分类" clearable style="width: 150px">
                    <el-option label="操作指南" value="guide" />
                    <el-option label="故障处理" value="troubleshooting" />
                    <el-option label="维护保养" value="maintenance" />
                    <el-option label="安全规范" value="safety" />
                    <el-option label="技术资料" value="technical" />
                  </el-select>
                </el-form-item>
                <el-form-item label="标签">
                  <el-input
                    v-model="knowledgeQuery.tags"
                    placeholder="请输入标签"
                    clearable
                    style="width: 150px"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" :icon="Search" @click="searchKnowledge">查询</el-button>
                  <el-button :icon="Refresh" @click="resetKnowledgeQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 操作按钮 -->
            <el-card shadow="never" class="action-card">
              <el-row :gutter="16">
                <el-col :span="24">
                  <el-button type="primary" plain :icon="Plus" @click="handleAddKnowledge">新增知识</el-button>
                  <el-button plain :icon="Collection" @click="manageCategories">品类管理</el-button>
                </el-col>
              </el-row>
            </el-card>

            <!-- 知识列表 -->
            <div class="knowledge-list">
              <div
                v-for="item in knowledgeList"
                :key="item.id"
                class="knowledge-item"
                @click="viewKnowledge(item)"
              >
                <div class="knowledge-header">
                  <h3 class="knowledge-title">{{ item.title }}</h3>
                  <div class="knowledge-meta">
                    <el-tag size="small" :type="getCategoryTag(item.category)">
                      {{ getCategoryText(item.category) }}
                    </el-tag>
                    <span class="knowledge-author">{{ item.author }}</span>
                    <span class="knowledge-date">{{ item.createDate }}</span>
                  </div>
                </div>
                <div class="knowledge-content">
                  <p>{{ item.summary }}</p>
                </div>
                <div class="knowledge-footer">
                  <div class="knowledge-tags">
                    <el-tag
                      v-for="tag in item.tags"
                      :key="tag"
                      size="small"
                      type="info"
                      effect="plain"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                  <div class="knowledge-stats">
                    <span class="stat-item">
                      <el-icon><View /></el-icon>
                      {{ item.views }}
                    </span>
                    <span class="stat-item">
                      <el-icon><Star /></el-icon>
                      {{ item.likes }}
                    </span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 分页 -->
            <div class="pagination-section">
              <Pagination
                :current-page="knowledgePagination.currentPage"
                :page-size="knowledgePagination.pageSize"
                :total="knowledgePagination.total"
                @pagination="handleKnowledgePagination"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- 外部链接 -->
        <el-tab-pane label="外部链接" name="links">
          <div class="tab-content">
            <!-- 查询条件 -->
            <div class="query-section">
              <el-form :model="linkQuery" inline>
                <el-form-item label="链接名称">
                  <el-input
                    v-model="linkQuery.name"
                    placeholder="请输入链接名称"
                    clearable
                    style="width: 200px"
                  />
                </el-form-item>
                <el-form-item label="分类">
                  <el-select v-model="linkQuery.category" placeholder="请选择分类" clearable style="width: 150px">
                    <el-option label="政府网站" value="government" />
                    <el-option label="行业网站" value="industry" />
                    <el-option label="技术资源" value="technical" />
                    <el-option label="合作伙伴" value="partner" />
                    <el-option label="其他" value="other" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" :icon="Search" @click="searchLinks">查询</el-button>
                  <el-button :icon="Refresh" @click="resetLinkQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 操作按钮 -->
            <el-card shadow="never" class="action-card">
              <el-row :gutter="16">
                <el-col :span="24">
                  <el-button type="primary" plain :icon="Plus" @click="handleAddLink">新增链接</el-button>
                  <el-button plain :icon="Check" @click="checkAllLinks">检查链接</el-button>
                </el-col>
              </el-row>
            </el-card>

            <!-- 链接网格 -->
            <div class="link-grid">
              <div
                v-for="link in linkList"
                :key="link.id"
                class="link-item"
                @click="openLink(link)"
              >
                <div class="link-icon">
                  <el-icon><Link /></el-icon>
                </div>
                <div class="link-info">
                  <div class="link-name">{{ link.name }}</div>
                  <div class="link-url">{{ link.url }}</div>
                  <div class="link-description">{{ link.description }}</div>
                </div>
                <div class="link-meta">
                  <el-tag size="small" :type="getLinkCategoryTag(link.category)">
                    {{ getLinkCategoryText(link.category) }}
                  </el-tag>
                  <div class="link-status">
                    <el-tag
                      size="small"
                      :type="link.status === 'active' ? 'success' : 'danger'"
                    >
                      {{ link.status === 'active' ? '正常' : '异常' }}
                    </el-tag>
                  </div>
                </div>
                <div class="link-actions">
                  <el-button type="primary" link @click.stop="editLink(link)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button type="danger" link @click.stop="deleteLink(link)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 分页 -->
            <div class="pagination-section">
              <Pagination
                :current-page="linkPagination.currentPage"
                :page-size="linkPagination.pageSize"
                :total="linkPagination.total"
                @pagination="handleLinkPagination"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, Plus, Download, Refresh, Check,
  User, Document, Reading, Link, FolderOpened,
  Edit, Delete, View, Star, Collection, Phone
} from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination/index.vue'

// 页面数据
const activeTab = ref('contacts')

// 统计数据
const statsData = reactive({
  totalContacts: 45,
  totalDocuments: 128,
  totalKnowledge: 67,
  totalLinks: 23
})

// 联系人相关数据
const contactQuery = reactive({
  name: '',
  department: '',
  position: ''
})

const contactList = ref<any[]>([])
const contactPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 文档相关数据
const documentQuery = reactive({
  name: '',
  type: '',
  dateRange: null as any
})

const documentList = ref<any[]>([])
const documentPagination = reactive({
  currentPage: 1,
  pageSize: 12,
  total: 0
})

// 知识库相关数据
const knowledgeQuery = reactive({
  title: '',
  category: '',
  tags: ''
})

const knowledgeList = ref<any[]>([])
const knowledgePagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
})

// 外部链接相关数据
const linkQuery = reactive({
  name: '',
  category: ''
})

const linkList = ref<any[]>([])
const linkPagination = reactive({
  currentPage: 1,
  pageSize: 12,
  total: 0
})

// 统一工具与全量模拟数据源
const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
const randomChoice = <T>(arr: T[]): T => arr[randInt(0, arr.length - 1)]
const pad2 = (n: number) => (n < 10 ? `0${n}` : `${n}`)
const formatDate = (d: Date) => `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`

const allContacts = ref<any[]>([])
const allDocuments = ref<any[]>([])
const allKnowledge = ref<any[]>([])
const allLinks = ref<any[]>([])

// 生成模拟数据
const generateMockContacts = () => {
  if (allContacts.value.length) return
  const deps = ['management', 'technical', 'safety', 'maintenance', 'external']
  const positions = ['supervisor', 'engineer', 'technician', 'operator', 'other']
  const statuses = ['active', 'inactive', 'leave']
  const count = randInt(10, 50)
  const base: any[] = []
  for (let i = 0; i < count; i++) {
    base.push({
      id: i + 1000,
      name: `联系人-${i + 1}`,
      department: randomChoice(deps),
      position: randomChoice(positions),
      phone: `138${pad2(randInt(10, 99))}${pad2(randInt(10, 99))}${pad2(randInt(10, 99))}`,
      email: `user${i + 1}@example.com`,
      office: `办公楼${randInt(101, 505)}`,
      specialties: '水利工程/设备维护',
      status: randomChoice(statuses)
    })
  }
  allContacts.value = base
}

const applyContacts = () => {
  let data = [...allContacts.value]
  if (contactQuery.name?.trim()) {
    const kw = contactQuery.name.trim().toLowerCase()
    data = data.filter(i => `${i.name}`.toLowerCase().includes(kw))
  }
  if (contactQuery.department) data = data.filter(i => i.department === contactQuery.department)
  if (contactQuery.position) data = data.filter(i => i.position === contactQuery.position)
  linkPagination.total // no-op to avoid lints
  contactPagination.total = data.length
  const startIdx = (contactPagination.currentPage - 1) * contactPagination.pageSize
  contactList.value = data.slice(startIdx, startIdx + contactPagination.pageSize)
}

const generateMockDocuments = () => {
  if (allDocuments.value.length) return
  const types = ['technical', 'management', 'manual', 'training', 'other']
  const authors = ['张三', '李四', '王五', '赵六']
  const count = randInt(10, 50)
  const base: any[] = []
  for (let i = 0; i < count; i++) {
    const d = new Date(2023, randInt(0, 11), randInt(1, 28))
    base.push({
      id: i + 2000,
      name: `文档-${i + 1}.pdf`,
      type: randomChoice(types),
      size: randInt(50_000, 5_000_000),
      uploadDate: formatDate(d),
      author: randomChoice(authors)
    })
  }
  allDocuments.value = base
}

const applyDocuments = () => {
  let data = [...allDocuments.value]
  if (documentQuery.name?.trim()) {
    const kw = documentQuery.name.trim().toLowerCase()
    data = data.filter(i => `${i.name}`.toLowerCase().includes(kw))
  }
  if (documentQuery.type) data = data.filter(i => i.type === documentQuery.type)
  if (Array.isArray(documentQuery.dateRange) && documentQuery.dateRange.length === 2) {
    const [start, end] = documentQuery.dateRange
    const startTs = new Date(start + ' 00:00:00').getTime()
    const endTs = new Date(end + ' 23:59:59').getTime()
    data = data.filter(i => {
      const ts = new Date(i.uploadDate).getTime()
      return ts >= startTs && ts <= endTs
    })
  }
  documentPagination.total = data.length
  const startIdx = (documentPagination.currentPage - 1) * documentPagination.pageSize
  documentList.value = data.slice(startIdx, startIdx + documentPagination.pageSize)
}

const generateMockKnowledge = () => {
  if (allKnowledge.value.length) return
  const cats = ['guide', 'troubleshooting', 'maintenance', 'safety', 'technical']
  const authors = ['张三', '李四', '王五', '赵六']
  const count = randInt(10, 50)
  const base: any[] = []
  for (let i = 0; i < count; i++) {
    base.push({
      id: i + 3000,
      title: `知识条目-${i + 1}`,
      category: randomChoice(cats),
      summary: '示例知识摘要内容',
      content: '...',
      author: randomChoice(authors),
      createDate: formatDate(new Date(2023, randInt(0, 11), randInt(1, 28))),
      tags: ['水库', '安全', '维护', `标签${randInt(1,5)}`],
      views: randInt(20, 500),
      likes: randInt(0, 120)
    })
  }
  allKnowledge.value = base
}

const applyKnowledge = () => {
  let data = [...allKnowledge.value]
  if (knowledgeQuery.title?.trim()) {
    const kw = knowledgeQuery.title.trim().toLowerCase()
    data = data.filter(i => `${i.title}`.toLowerCase().includes(kw))
  }
  if (knowledgeQuery.category) data = data.filter(i => i.category === knowledgeQuery.category)
  if (knowledgeQuery.tags?.trim()) {
    const kw = knowledgeQuery.tags.trim().toLowerCase()
    data = data.filter(i => i.tags.join(',').toLowerCase().includes(kw))
  }
  knowledgePagination.total = data.length
  const startIdx = (knowledgePagination.currentPage - 1) * knowledgePagination.pageSize
  knowledgeList.value = data.slice(startIdx, startIdx + knowledgePagination.pageSize)
}

const generateMockLinks = () => {
  if (allLinks.value.length) return
  const cats = ['government', 'industry', 'technical', 'partner', 'other']
  const statuses = ['active', 'inactive']
  const count = randInt(10, 50)
  const base: any[] = []
  for (let i = 0; i < count; i++) {
    base.push({
      id: i + 4000,
      name: `外部链接-${i + 1}`,
      url: `http://example.com/${i + 1}`,
      description: '示例链接描述',
      category: randomChoice(cats),
      status: randomChoice(statuses)
    })
  }
  allLinks.value = base
}

const applyLinks = () => {
  let data = [...allLinks.value]
  if (linkQuery.name?.trim()) {
    const kw = linkQuery.name.trim().toLowerCase()
    data = data.filter(i => `${i.name}`.toLowerCase().includes(kw))
  }
  if (linkQuery.category) data = data.filter(i => i.category === linkQuery.category)
  linkPagination.total = data.length
  const startIdx = (linkPagination.currentPage - 1) * linkPagination.pageSize
  linkList.value = data.slice(startIdx, startIdx + linkPagination.pageSize)
}

// 联系人操作方法
const loadContactData = () => {
  generateMockContacts()
  applyContacts()
}

const searchContacts = () => {
  contactPagination.currentPage = 1
  loadContactData()
}

const resetContactQuery = () => {
  Object.assign(contactQuery, {
    name: '',
    department: '',
    position: ''
  })
  contactPagination.currentPage = 1
  loadContactData()
}

const deleteContact = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除联系人"${row.name}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const idx = allContacts.value.findIndex(i => i.id === row.id)
    if (idx !== -1) allContacts.value.splice(idx, 1)
    applyContacts()
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

const handleContactPagination = (pagination: any) => {
  contactPagination.currentPage = pagination.page
  contactPagination.pageSize = pagination.limit
  loadContactData()
}

// 文档操作方法
const loadDocumentData = () => {
  generateMockDocuments()
  applyDocuments()
}

const searchDocuments = () => {
  documentPagination.currentPage = 1
  loadDocumentData()
}

const resetDocumentQuery = () => {
  Object.assign(documentQuery, {
    name: '',
    type: '',
    dateRange: null
  })
  documentPagination.currentPage = 1
  loadDocumentData()
}

const deleteDocument = async (doc: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除文档"${doc.name}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const idx = allDocuments.value.findIndex(i => i.id === doc.id)
    if (idx !== -1) allDocuments.value.splice(idx, 1)
    applyDocuments()
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

const handleDocumentPagination = (pagination: any) => {
  documentPagination.currentPage = pagination.page
  documentPagination.pageSize = pagination.limit
  loadDocumentData()
}

// 知识库操作方法
const loadKnowledgeData = () => {
  generateMockKnowledge()
  applyKnowledge()
}

const searchKnowledge = () => {
  knowledgePagination.currentPage = 1
  loadKnowledgeData()
}

const resetKnowledgeQuery = () => {
  Object.assign(knowledgeQuery, {
    title: '',
    category: '',
    tags: ''
  })
  knowledgePagination.currentPage = 1
  loadKnowledgeData()
}

const handleKnowledgePagination = (pagination: any) => {
  knowledgePagination.currentPage = pagination.page
  knowledgePagination.pageSize = pagination.limit
  loadKnowledgeData()
}

// 外部链接操作方法
const loadLinkData = () => {
  generateMockLinks()
  applyLinks()
}

const searchLinks = () => {
  linkPagination.currentPage = 1
  loadLinkData()
}

const resetLinkQuery = () => {
  Object.assign(linkQuery, {
    name: '',
    category: ''
  })
  linkPagination.currentPage = 1
  loadLinkData()
}

const deleteLink = async (link: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除链接"${link.name}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const idx = allLinks.value.findIndex(i => i.id === link.id)
    if (idx !== -1) allLinks.value.splice(idx, 1)
    applyLinks()
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

const handleLinkPagination = (pagination: any) => {
  linkPagination.currentPage = pagination.page
  linkPagination.pageSize = pagination.limit
  loadLinkData()
}

// 辅助映射与工具方法补齐
const getDepartmentTag = (dep: string) => {
  const map: Record<string, string> = {
    management: 'success',
    technical: 'info',
    safety: 'warning',
    maintenance: 'danger',
    external: 'info'
  }
  return map[dep] || 'info'
}
const getDepartmentText = (dep: string) => {
  const map: Record<string, string> = {
    management: '管理部门',
    technical: '技术部门',
    safety: '安全管理',
    maintenance: '运维保障',
    external: '外部单位'
  }
  return map[dep] || dep
}
const getContactStatusTag = (status: string) => {
  const map: Record<string, string> = { active: 'success', inactive: 'info', leave: 'warning' }
  return map[status] || 'info'
}
const getContactStatusText = (status: string) => {
  const map: Record<string, string> = { active: '在岗', inactive: '离线', leave: '请假' }
  return map[status] || status
}
const getDocumentTypeText = (type: string) => {
  const map: Record<string, string> = {
    technical: '技术文档',
    management: '管理制度',
    manual: '操作手册',
    training: '培训资料',
    other: '其他'
  }
  return map[type] || type
}
const formatFileSize = (size: number) => {
  if (size < 1024) return `${size} B`
  const units = ['KB', 'MB', 'GB']
  let s = size
  let idx = -1
  while (s >= 1024 && idx < units.length - 1) {
    s /= 1024
    idx++
  }
  return `${s.toFixed(1)} ${units[idx]}`
}
const getCategoryTag = (cat: string) => {
  const map: Record<string, string> = { guide: 'success', troubleshooting: 'warning', maintenance: 'info', safety: 'danger', technical: 'success' }
  return map[cat] || 'info'
}
const getCategoryText = (cat: string) => {
  const map: Record<string, string> = { guide: '指南', troubleshooting: '故障排查', maintenance: '维护保养', safety: '安全', technical: '技术' }
  return map[cat] || cat
}
const getLinkCategoryTag = (cat: string) => {
  const map: Record<string, string> = { government: 'success', industry: 'info', technical: 'warning', partner: 'success', other: 'info' }
  return map[cat] || 'info'
}
const getLinkCategoryText = (cat: string) => {
  const map: Record<string, string> = { government: '政府', industry: '行业', technical: '技术', partner: '合作伙伴', other: '其他' }
  return map[cat] || cat
}

// 交互方法补齐：联系人
const handleAddContact = () => {
  const id = Date.now()
  const newItem = {
    id,
    name: `联系人-${allContacts.value.length + 1}`,
    department: 'management',
    position: 'operator',
    phone: `138${pad2(randInt(10, 99))}${pad2(randInt(10, 99))}${pad2(randInt(10, 99))}`,
    email: `new${allContacts.value.length + 1}@example.com`,
    office: `办公楼${randInt(101, 505)}`,
    specialties: '水利工程/设备维护',
    status: 'active'
  }
  allContacts.value.unshift(newItem)
  applyContacts()
  ElMessage.success('新增联系人成功')
}
const exportContacts = () => {
  let data = [...allContacts.value]
  if (contactQuery.name?.trim()) {
    const kw = contactQuery.name.trim().toLowerCase()
    data = data.filter(i => `${i.name}`.toLowerCase().includes(kw))
  }
  if (contactQuery.department) data = data.filter(i => i.department === contactQuery.department)
  if (contactQuery.position) data = data.filter(i => i.position === contactQuery.position)
  const header = ['姓名','部门','职位','电话','邮箱','办公地点','状态']
  const rows = data.map(i => [i.name, getDepartmentText(i.department), i.position, i.phone, i.email, i.office, getContactStatusText(i.status)].join(','))
  const csv = [header.join(','), ...rows].join('\n')
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `联系人导出_${formatDate(new Date())}.csv`
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('通讯录已导出')
}
const viewContactDetail = (row: any) => {
  ElMessage.info(`查看联系人：${row.name}`)
}
const editContact = (row: any) => {
  ElMessage.info(`编辑联系人：${row.name}（功能暂未实现）`)
}
const callContact = (row: any) => {
  try {
    window.open(`tel:${row.phone}`)
  } catch {}
  ElMessage.success(`已尝试拨打：${row.phone}`)
}
const handleContactSizeChange = (size: number) => {
  contactPagination.pageSize = size
  contactPagination.currentPage = 1
  loadContactData()
}
const handleContactCurrentChange = (page: number) => {
  contactPagination.currentPage = page
  loadContactData()
}

// 交互方法补齐：文档
const handleAddDocument = () => {
  const id = Date.now()
  const newDoc = {
    id,
    name: `文档-${allDocuments.value.length + 1}.pdf`,
    type: 'technical',
    size: randInt(50_000, 5_000_000),
    uploadDate: formatDate(new Date()),
    author: '系统'
  }
  allDocuments.value.unshift(newDoc)
  applyDocuments()
  ElMessage.success('文档上传成功')
}
const createFolder = () => {
  ElMessage.info('新建文件夹功能暂未实现')
}
const viewDocument = (doc: any) => {
  ElMessage.info(`预览文档：${doc.name}`)
}
const downloadDocument = (doc: any) => {
  const blob = new Blob([`模拟文档内容：${doc.name}`], { type: 'application/octet-stream' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = doc.name
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('开始下载文档')
}
const editDocument = (doc: any) => {
  ElMessage.info(`编辑文档：${doc.name}（功能暂未实现）`)
}

// 交互方法补齐：知识库
const handleAddKnowledge = () => {
  const id = Date.now()
  const newItem = {
    id,
    title: `知识条目-${allKnowledge.value.length + 1}`,
    category: 'guide',
    summary: '示例知识摘要内容',
    content: '...',
    author: '系统',
    createDate: formatDate(new Date()),
    tags: ['水库','新增'],
    views: 0,
    likes: 0
  }
  allKnowledge.value.unshift(newItem)
  applyKnowledge()
  ElMessage.success('新增知识成功')
}
const manageCategories = () => {
  ElMessage.info('品类管理功能暂未实现')
}
const viewKnowledge = (item: any) => {
  ElMessage.info(`查看知识：${item.title}`)
}

// 交互方法补齐：外部链接
const handleAddLink = () => {
  const id = Date.now()
  const newLink = {
    id,
    name: `外部链接-${allLinks.value.length + 1}`,
    url: `https://example.com/${allLinks.value.length + 1}`,
    description: '示例链接描述',
    category: 'other',
    status: 'active'
  }
  allLinks.value.unshift(newLink)
  applyLinks()
  ElMessage.success('新增链接成功')
}
const checkAllLinks = async () => {
  // 模拟检查，可扩展为真实请求
  await new Promise(r => setTimeout(r, 300))
  const ids = linkList.value.map(i => i.id)
  allLinks.value = allLinks.value.map(i => ids.includes(i.id) ? { ...i, status: 'active' } : i)
  applyLinks()
  ElMessage.success('检查完成，全部可访问')
}
const openLink = (link: any) => {
  try {
    window.open(link.url, '_blank')
  } catch {
    ElMessage.warning('无法打开链接')
  }
}
const editLink = (link: any) => {
  ElMessage.info(`编辑链接：${link.name}（功能暂未实现）`)
}

// 标签切换统一加载
const loadTabData = (name: string) => {
  switch (name) {
    case 'contacts':
      loadContactData()
      break
    case 'documents':
      loadDocumentData()
      break
    case 'knowledge':
      loadKnowledgeData()
      break
    case 'links':
      loadLinkData()
      break
  }
}

// Tabs 切换事件
const handleTabChange = (name: string) => {
  activeTab.value = name
  loadTabData(name)
}

// 页面初始化
onMounted(() => {
  loadTabData(activeTab.value)
})
</script>

<style scoped>
.related-info {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-description {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  background: linear-gradient(135deg, #409eff, #66b1ff);
  color: white;
  font-size: 24px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.main-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.tab-content {
  padding: 20px;
}

.query-section {
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 16px;
}

.action-card {
  margin-bottom: 16px;
  border: 1px solid #e4e7ed;
}

.table-card {
  margin-bottom: 16px;
}

.pagination-section {
  margin-top: 16px;
  text-align: right;
}

/* 文档网格样式 */
.document-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.document-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.document-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.document-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f9ff;
  border-radius: 8px;
  margin-right: 12px;
  font-size: 24px;
  color: #409eff;
}

.document-info {
  flex: 1;
}

.document-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.document-meta {
  display: flex;
  gap: 8px;
  margin-bottom: 4px;
}

.document-type {
  color: #909399;
  font-size: 12px;
}

.document-size {
  color: #909399;
  font-size: 12px;
}

.document-date {
  color: #c0c4cc;
  font-size: 12px;
}

.document-actions {
  display: flex;
  gap: 4px;
}

/* 知识库列表样式 */
.knowledge-list {
  margin-bottom: 20px;
}

.knowledge-item {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  margin-bottom: 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.knowledge-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.knowledge-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.knowledge-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.knowledge-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.knowledge-author,
.knowledge-date {
  color: #909399;
  font-size: 14px;
}

.knowledge-content {
  margin-bottom: 16px;
}

.knowledge-content p {
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

.knowledge-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.knowledge-tags {
  display: flex;
  gap: 8px;
}

.knowledge-stats {
  display: flex;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 14px;
}

/* 链接网格样式 */
.link-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.link-item {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.link-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.link-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f9ff;
  border-radius: 8px;
  margin-bottom: 12px;
  font-size: 24px;
  color: #409eff;
}

.link-info {
  margin-bottom: 12px;
}

.link-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.link-url {
  color: #409eff;
  font-size: 14px;
  margin-bottom: 8px;
  word-break: break-all;
}

.link-description {
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
}

.link-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.link-actions {
  position: absolute;
  top: 16px;
  right: 16px;
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.link-item:hover .link-actions {
  opacity: 1;
}

:deep(.el-tabs__header) {
  margin: 0;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

:deep(.el-tabs__item) {
  height: 50px;
  line-height: 50px;
  font-weight: 500;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.el-pagination) {
  justify-content: flex-end;
}
</style>